package com.sdnu.service.controller;


import com.sdnu.common.Result.R;
import com.sdnu.common.exceptionhandle.CustomerException;
import com.sdnu.service.entity.ucenter.User;
import com.sdnu.service.entity.ucenter.excel.UserDemo;
import com.sdnu.service.entity.ucenter.vo.LoginVo;
import com.sdnu.service.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Zhao YunLai
 * @since 2021-12-05
 */
@RestController
@RequestMapping("/ucenter/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("登录")
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo){
        User userInfo = null;
        try {
            userInfo = userService.login(loginVo);
        } catch(CustomerException e){
            return R.error().message(e.getMsg());
        }
        return R.ok().data("userInfo",userInfo);
    }

    @PostMapping("changePassword")
    public R changePassword(@RequestBody LoginVo loginVo){
        try {
            userService.changePassword(loginVo);
        } catch (CustomerException e) {
            return R.error().message(e.getMsg());
        }
        return R.ok();
    }


    @ApiOperation("批量添加用户，根据excel，表格格式固定")
    @PostMapping("addUserBatch")
    public R addUserBatch(MultipartFile file){

        userService.addUserBatch(file,userService);
        return R.ok();
    }


    @ApiOperation("增加用户")
    @PostMapping("addOneUser")
    public R addOneUser(@RequestBody UserDemo userDemo){
        boolean b = userService.addOneUser(userDemo);
        return R.ok();
    }

    @ApiOperation("更新用户")
    @PutMapping("update")
    public R updateUser(@RequestBody User user){
        boolean b = userService.updateById(user);
//日志
        System.out.println(new Date()+":"+user.getName()+"-->修改了信息,user:{phone:"+user.getPhone()+",email:"+user.getEmail()+
                ",avatar:"+user.getAvatar()+"}");
        return b?R.ok():R.error();
    }

    @ApiOperation("删除用户")
    @DeleteMapping("delete/{id}")
    public R deleteUser(@PathVariable String id){
        boolean b = userService.removeById(id);
        return b?R.ok():R.error();
    }

    @ApiOperation("查询用户")
    @GetMapping("get/{id}")
    public R getUserById(@PathVariable String id){
        User user = userService.getById(id);

        //查询了用户
        System.out.println(new Date()+":进入了-->"+user.getName()+"的详情页");
        return R.ok().data("user",user);
    }
}

